package com.example.configuration;

import com.example.bean.Property;
import com.example.data.ConfigDataHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigServer
@Slf4j
public class ConfigServerConfiguration implements EnvironmentRepository {
    @Resource
    ConfigDataHandler configDataHandler;

    @Override
    public Environment findOne(String application, String profile, String label) {
        log.info("application: {}, profile: {}, label:{}", application, profile, label);
        Environment environment = new Environment(application, profile, label, null, null);
        List<Property> propertyList = configDataHandler.find(application, profile, label);
        Map<String, String> source = propertyList.stream().collect(Collectors.toMap(Property::getKey, Property::getValue));
        environment.add(new PropertySource(application, source));
        return environment;
    }
}
